package com.haiyou.dc.thread.test1;

/**
 * 线程安全：保证数据的准确性
 * 方法1：锁方法
 * 方法2：锁块
 */
public class SynBlockTest01 {

    public static void main(String[] args) {
        Account account = new Account(100, "结婚礼金");
        SysBlockSafeDrawing you = new SysBlockSafeDrawing(account, 80, "伤心的你");
        SysBlockSafeDrawing wife = new SysBlockSafeDrawing(account, 90, "开心的她");
        you.start();
        wife.start();
    }

}


class SysBlockSafeDrawing extends Thread {

    private int drawMoney;
    private int packetMoney;
    private Account account;

    public SysBlockSafeDrawing(Account account, int drawMoney, String name) {
        super(name);
        this.account = account;
        this.drawMoney = drawMoney;
    }

    @Override
    public void run() {
        test();
    }

    /**
     * 目标不对，锁定失败，应该锁的是account，不是this
     */
    public void test() {

        //代码性能优化
        if (account.money <= 0) {
            return;
        }
        //同步块
        synchronized (account) {
            if (account.money - this.drawMoney < 0) {
                return;
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            account.money -= this.drawMoney;
            this.packetMoney += this.drawMoney;

            System.out.println(this.getName() + "--->账号余额=" + account.money);
            System.out.println(this.getName() + "--->口袋余额=" + this.packetMoney);
        }
    }
}